package com.study.base.io.nio.demo.noblock;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * User: 27010
 * DateTime: 2017/8/27 10:28
 */
public class NIOClient {
    private SocketChannel channel;
    private Selector selector;
    private ByteBuffer buffer;

    private List<ByteBuffer> buffers;

    public NIOClient(String host, int port) throws IOException {
        selector = Selector.open();
        channel = SocketChannel.open();
        buffer = ByteBuffer.allocate(8 * 1000);
        buffers = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            buffers.add(ByteBuffer.allocate(100));
        }
        channel.connect(new InetSocketAddress(host, port));
    }

    public void send(String msg) {
        buffer.put(msg.getBytes());
        try {
            channel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     public void send(int i, String msg) {
         Thread.currentThread().interrupt(); //放到这，会使得channel关闭，并抛出ClosedByInterruptException异常。 是不是不太合理。
        buffers.get(i).put(msg.getBytes());
        try {
            int length = channel.write(buffer);
            if(length<msg.getBytes().length){
                System.out.println(length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Thread.currentThread().interrupt(); 放到这，没影响

    }

    public static void main(String[] args) throws IOException, InterruptedException {
        NIOClient nioClient = new NIOClient("127.0.0.1", 89);

//        Runnable runnable = () -> {
//            nioClient.send("ii");
//        };
//        Thread thread = new Thread(runnable);
//        thread.start();

        for (int i = 0; i < 2; i++) {
            int num = i;
            Runnable runnable = () -> {
                nioClient.send(num,"iioooooooooooooooooggggggggggggggggg");
            };
            Thread thread = new Thread(runnable);
            thread.start();
        }

        Thread.sleep(100000000);
    }

}
